<?php
namespace app\policy\home;
use think\Db;
use app\index\controller\Home;
use app\policy\tools\WxMsg;
class Index extends Home
{
    public function deptInfo(){
        $district_list =explode( ',',str_replace('，',',',trim(module_config('policy.district_list'))));
		$dept_list =explode( ',',str_replace('，',',',trim(module_config('policy.dept_list'))));
        $result = [
            'code' => 1,
            'list' => [
                "district_list"=>$district_list,
                "dept_list"=>$dept_list
            ]
        ];
        return json($result);
    }
    public function getDeptDetails(){
         if(request()->isPost()){
            $post = request()->post();
            $result = [
                'code' => 1,
                'data' =>Db::name('policy_dept_details')->where($post)->find()
            ];
            return json($result);
        }
       
    }
    public function policyList(){
        if(request()->isPost()){
            $post = request()->post();
            $limit=isset($post['limit'])?$post['limit']:0;
            return json([
                'code' => 1,
                'list' =>Db::name('policy_article')
                ->field('id,title,date')
                ->whereTime('date',$post['date']&&$post['date'][0]?$post['date']:0)
                ->order('date',$post['sort'])
                ->limit($limit)
                ->select()
            ]);
        }
        
    }
    public function getPolicyDetails(){
        if(request()->isPost()){
            $post = request()->post();
            $data=Db::name('policy_article')->where(['id'=>$post['id']])->find();
            $user=Db::name('user')->where(['openid'=>$post['openid']])->find();
            if(empty($user)){
                $data['is_collect']=false;
                Db::name('user')->insert(['openid'=>$post['openid'],'history'=>$post['id']]);
            }else{
                if($user['collect'])
                    $data['is_collect']=in_array($post['id'],explode(',',$user['collect']));
                
                if($user['history']){
                    $arr = array_flip(explode(',',$user['history']));
                    unset($arr[$post['id']]);
                    $arr=array_flip($arr);
                    array_unshift($arr,$post['id']);
                    $user['history']=implode(',',$arr);
                }else
                    $user['history']=$post['id'];
                Db::name('user')->where(['openid'=>$post['openid']])->update(['history'=>$user['history']]);
            }
            return json([
                'code' => 1,
                'data' =>$data
            ]);
        }
        
    }
    public function setCollect(){
        if(request()->isPost()){
            $post = request()->post();
            $user=Db::name('user')->where(['openid'=>$post['openid']])->find();
            $arr=$user['collect']?explode(',',$user['collect']):[];
            if($post['is'] && !in_array($post['id'],$arr))
                array_unshift($arr,$post['id']);
            if(!$post['is'] && in_array($post['id'],$arr)){
                $arr = array_flip($arr);
                unset($arr[$post['id']]);
                $arr = array_flip($arr);
            }
            Db::name('user')->where(['openid'=>$post['openid']])->update(['collect'=>implode(',',$arr)]);
            return json([
                'code' => 1,
                'data' =>true
            ]); 
        }
    }
    public function getCollect(){
        if(request()->isPost()){
            $post = request()->post();
            $user=Db::name('user')->where($post)->find();
            $list=$user && $user['collect']?Db::name('policy_article')->whereIn('id',$user['collect'])->field('id,title,date')->select():[];
            return json([
                'code' => 1,
                'list' =>$list
            ]);
        }
    }
    public function getHistory(){
        if(request()->isPost()){
            $post = request()->post();
            $user=Db::name('user')->where($post)->find();
            $list=$user && $user['history']?Db::name('policy_article')->whereIn('id',$user['history'])->field('id,title,date')->select():[];
            return json([
                'code' => 1,
                'list' =>$list
            ]);
        }
    }
    public function getCode(){
        if(request()->isPost()){
            $post = request()->post();
            $s = file_get_contents($post['url']);
            $s = json_decode($s, true);
            return json([
                'code' => 1,
                'data' =>$s
            ]);
        }
    }
    public function msgBoard(){
        if(request()->isPost()){
            $post = request()->post();
            $post['create_time']= date("Y-m-d H:i:s",time());
            Db::name('msgboard')->insert($post);
            return json([
                'code' => 1,
                'data' =>true
            ]);
        }
    }
    public function replyMsg($str){
        $district_list =explode( ',',str_replace('，',',',trim(module_config('policy.district_list'))));
		$dept_list =explode( ',',str_replace('，',',',trim(module_config('policy.dept_list'))));
        $tel_key_arr=[];
        foreach ($district_list as $val){
            if(mb_strpos($str,$val)!==false)
                $tel_key_arr['district']=$val;
        }
        if(isset($tel_key_arr['district'])){
            foreach ($dept_list as $val){
                if(mb_strpos($str,$val)!==false)
                    $tel_key_arr['dept']=$val;
            }
        }
        
        if(count($tel_key_arr)===2){
            $res=Db::name('policy_dept_details')->where($tel_key_arr)->find();
            $text=$res?$res['tel']:'该部门的电话尚未收录！';
            $data=[
                "msgtype"=>"text",
                "text"=>[
                    'content'=>$text
                ]
            ];
        }else{
            $res=Db::name('policy_article')->whereLike('title',"%$str%")->find();
            if($res){
                $msg=new WxMsg();
                $cover=json_decode($msg->upload_cover(),true);
                $data=[
                    "msgtype"=>"miniprogrampage",
                    "miniprogrampage"=>[
                        'title'=>$res['title'],
                        'pagepath'=>'pages/policy/details?id'.$res['id'],
                        "thumb_media_id"=>$cover['media_id']
                    ]
                ];
                
            }else{
                $data=[
                    "msgtype"=>"text",
                    "text"=>[
                        'content'=>'未搜索到该政策！'
                    ]
                ];
            }
        }
        return $data;
    }
    public function wxApi(){
        if(request()->isPost()){
            $post = request()->post();
            $data = $this->replyMsg($post['Content']);
            $data['touser']=$post['FromUserName'];
            $msg=new WxMsg();
            $msg->send_kefu($data);
        }
    }
}